<?php

declare (strict_types=1);

namespace app\middleware;

use think\facade\Cookie;
use app\model\User;
use app\model\Menu;
use think\facade\View;

class AdminAuth
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $request->test = 'fuckyou';
        //无需登录页面
        $noNeedLogin = [
            'admin/user/login',//登录
            'admin/user/logout',//登出
        ];

        //登录后无需验证的页面
        $no_need_to_check = [
            'admin/upload/uploadpic',//上传显示页
            'admin/upload/uploadpics',//多图上传显示页
            'admin/upload/file',
            'admin/js/js',
            'admin/user/skin',//皮肤切换
        ];

        $status = false;
        $request->url = str_replace('.', '/', $request->controller(true).'/'.$request->action(true));

        //放过无需登录页面
        if (in_array($request->url, $noNeedLogin)) {
            return $next($request);
        }

        //登录判断
        $auth = Cookie::get('auth');

        if (!$auth || strlen($auth) < 64) {
            return redirect((string) url('admin/user/login'));
        }
        list($identifier, $token) = str_split($auth, 32);
        if (ctype_alnum($identifier) && ctype_alnum($token)) {
            $request->user = User::where(['identifier' => $identifier,'token' => $token,'status' => 1])->find();
            if ($request->user) {
                if ($token == $request->user['token'] && $request->user['identifier'] == password($request->user['uid'] . md5($request->user['username'] . $request->user['salt']))) {
                    $status = true;
                }
            }
        }
        if (!$status) {
            return redirect((string) url('admin/user/login'));
        }

        if (in_array($request->url, $no_need_to_check)) {
            return $next($request);
        }
        #菜单
        if ($request->user) {
            $menus = Menu::field('id,pid,title,url,icon')->where("status=1 and id in({$request->user->group->auth})")->order('o', 'asc')->select()->toArray();
            $menus = categorize_and_sort_hierarchy($menus);
            $current_menu = Menu::field('id,pid,title,url,icon,tips,status')->where(['url' => $request->url])->find();
            View::assign('current_menu', $current_menu);
            View::assign('current_menu_father', $current_menu->father ?? $current_menu);
            View::assign('menus', $menus);
            View::assign('user', $request->user);
        }
        //验证页面权限
        $current_url_id = Menu::where(['url' => $request->url])->find();

        if ($current_url_id && in_array($current_url_id->id, explode(',', $request->user->group->auth))) {
            return $next($request);
        } else {
            return redirect((string) url('admin/user/login'));
        }
        return $next($request);
    }
}
